#!/usr/bin/python3
# -*- coding: utf-8 -*-

import pymysql
from utili import IniConfig
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

DATABASE_CONF_FILE = os.path.join(BASE_DIR, 'configs\database_configs.ini')


class MysqlHandle:

    def __init__(self, host, port, user, password, database):
        self.con = None
        self.arguments = {
            "host": host,
            "port": port,
            "user": user,
            "password": password,
            "database": database,
            "charset": 'utf8'
        }

    def post(self, sql):
        with self:
            try:
                data = self.cursor.execute(sql)
                self.con.commit()

                return data
            except Exception as e:
                self.con.rollback()
                return e

    def get(self, sql, one=None):
        with self:
            try:
                self.cursor.execute(sql)
                if one:
                    return self.cursor.fetchone()
                else:
                    return self.cursor.fetchall()
            except Exception as e:
                return e

    def __enter__(self):
        if self.con is None:
            try:
                self.con = pymysql.connect(**self.arguments)
                self.cursor = self.con.cursor(pymysql.cursors.DictCursor)
            except Exception:
                raise "数据库连接失败！"

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.cursor.close()
        self.con.close()
        self.con = None


if __name__ == '__main__':
    iniConfig = IniConfig.IniCfg()
    sections = iniConfig.readSectionItems(DATABASE_CONF_FILE)
    # print(iniConfig.readOneSection("mysql_server"))
    print(iniConfig.prettySecToDic("mysql_server").get("host"))
    # print(iniConfig.checkSection("mysql_server"))
    # print(sections)
    mysql = MysqlHandle(iniConfig.prettySecToDic("mysql_server").get("host"),
                            int(iniConfig.prettySecToDic("mysql_server").get("port")),
                            iniConfig.prettySecToDic("mysql_server").get("user"),
                            iniConfig.prettySecToDic("mysql_server").get("password"),
                            iniConfig.prettySecToDic("mysql_server").get("database"))

    w = mysql.get("select * from  biz_article", "one")
    print(w)
